<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="等级体系名称" prop="systemName" class="system-name">
        <el-input
          v-model="queryParams.systemName"
          placeholder="请输入等级体系名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="等级名称" prop="levelName">
        <el-input
          v-model="queryParams.levelName"
          placeholder="请输入等级名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="该等级所需最低积分" prop="minPoints" class="min-points">
        <el-input
          v-model="queryParams.minPoints"
          placeholder="请输入该等级所需最低积分"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="该等级允许的最高积分" prop="maxPoints" class="max-points">
        <el-input
          v-model="queryParams.maxPoints"
          placeholder="请输入该等级允许的最高积分"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="等级状态" prop="levelStatus" class="level-status">
        <el-select v-model="queryParams.levelStatus" placeholder="请选择等级状态" clearable>
          <el-option
            v-for="dict in level_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['level:level:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Check"
          :disabled="multiple"
          @click="handleEnable"
          v-hasPermi="['level:level:remove']"
        >启用</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDisable"
          v-hasPermi="['level:level:remove']"
        >停用</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['level:level:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="levelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="等级体系名称" align="center" prop="systemName" />
      <el-table-column label="等级名称" align="center" prop="levelName" />
      <el-table-column label="等级图标" align="center" prop="levelIcon" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.levelIcon" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="该等级所需最低积分" align="center" prop="minPoints" class="min-points"/>
      <el-table-column label="该等级允许的最高积分" align="center" prop="maxPoints" class="max-points">
        <template #default="scope">
          <span v-if="scope.row.maxPoints == 2147483647">无上限</span>
          <span v-else>{{ scope.row.maxPoints }}</span>
        </template>
      </el-table-column>
      <el-table-column label="排序号" align="center" prop="sortOrder" />
      <el-table-column label="等级状态" align="center" prop="levelStatus">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.levelStatus == 1">启用</el-tag>
          <el-tag type="danger" v-else-if="scope.row.levelStatus == 2">停用</el-tag>
          <el-tag type="info" v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createdBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['level:level:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDisable(scope.row)" v-hasPermi="['level:level:remove']" v-if="scope.row.levelStatus == 1">停用</el-button>
          <el-button link type="success" icon="Check" @click="handleEnable(scope.row)" v-hasPermi="['level:level:remove']" v-if="scope.row.levelStatus == 2">启用</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户积分等级规则对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="levelRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="等级体系名称" prop="systemName" class="system-name">
          <el-input v-model="form.systemName" placeholder="请输入等级体系名称" />
        </el-form-item>
        <el-form-item label="等级名称" prop="levelName">
          <el-input v-model="form.levelName" placeholder="请输入等级名称" />
        </el-form-item>
        <el-form-item label="等级图标" prop="levelIcon">
          <image-upload v-model="form.levelIcon"/>
        </el-form-item>
        <el-form-item label="该等级所需的最低积分" prop="minPoints" class="min-points">
          <div style="display: flex; align-items: center; width: 100%;">
            <el-input v-model="form.minPoints" placeholder="请输入最低积分" style="flex: 1;" />
            <div style="width: 80px;"></div> <!-- 占位，与最高积分的复选框宽度相同 -->
          </div>
        </el-form-item>
        <el-form-item label="该等级允许的最高积分" prop="maxPoints" class="max-points">
          <div style="display: flex; align-items: center; width: 100%;">
            <el-input v-model="form.maxPoints" placeholder="请输入最高积分" :disabled="isUnlimited" style="flex: 1;" />
            <el-checkbox v-model="isUnlimited" @change="toggleUnlimited" style="margin-left: 10px; width: 70px;">无上限</el-checkbox>
          </div>
          <div class="el-form-item__description" style="font-size: 12px; color: #909399; margin-top: 5px;">
            注：只有最高等级（排序号最大）才能设置为无上限
          </div>
        </el-form-item>
        <el-form-item label="排序号" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Level">
import { listLevel, getLevel, disableLevel, addLevel, updateLevel, enableLevel } from "@/api/level/level";
import ImageUpload from "@/components/ImageUpload";
import ImagePreview from "@/components/ImagePreview";

const { proxy } = getCurrentInstance();
const { level_status } = proxy.useDict("level_status");

const UNLIMITED_POINTS = 2147483647;

const levelList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    systemName: null,
    levelName: null,
    minPoints: null,
    maxPoints: null,
    levelStatus: null,
  },
  rules: {
    systemName: [
      { required: true, message: "等级体系名称不能为空", trigger: "blur" }
    ],
    levelName: [
      { required: true, message: "等级名称不能为空", trigger: "blur" }
    ],
    minPoints: [
      { required: true, message: "该等级所需最低积分不能为空", trigger: "blur" },
      { 
        validator: (rule, value, callback) => {
          if (value === null || value === undefined || value === '') {
            callback()
          } else if (isNaN(Number(value))) {
            callback(new Error('请输入数字'))
          } else {
            callback()
          }
        }, 
        trigger: "blur" 
      }
    ],
    maxPoints: [
      { required: true, message: "该等级允许的最高积分不能为空", trigger: "blur" },
      { 
        validator: (rule, value, callback) => {
          if (value === null || value === undefined || value === '') {
            callback()
          } else if (isNaN(Number(value))) {
            callback(new Error('请输入数字'))
          } else {
            callback()
          }
        }, 
        trigger: "blur" 
      }
    ],
    sortOrder: [
      { required: true, message: "排序号不能为空", trigger: "blur" },
      { 
        validator: (rule, value, callback) => {
          if (value === null || value === undefined || value === '') {
            callback()
          } else if (isNaN(Number(value))) {
            callback(new Error('请输入数字'))
          } else {
            callback()
          }
        }, 
        trigger: "blur" 
      }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户积分等级规则列表 */
function getList() {
  loading.value = true;
  listLevel(queryParams.value).then(response => {
    levelList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 添加无上限标志
const isUnlimited = ref(false);

// 表单重置
function reset() {
  form.value = {
    id: null,
    levelCode: null,
    systemCode: null,
    systemName: null,
    levelName: null,
    levelIcon: null,
    minPoints: null,
    maxPoints: null,
    sortOrder: null,
    levelStatus: null,
    createdBy: null,
    createdTime: null,
    updatedBy: null,
    updatedTime: null,
    deletedFlag: null
  };
  isUnlimited.value = false;
  proxy.resetForm("levelRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户积分等级规则";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getLevel(_id).then(response => {
    form.value = response.data;
    // 检查是否是无上限设置
    isUnlimited.value = form.value.maxPoints === UNLIMITED_POINTS;
    open.value = true;
    title.value = "修改用户积分等级规则";
  });
}

// 切换无上限设置
function toggleUnlimited() {
  if (isUnlimited.value) {
    form.value.maxPoints = UNLIMITED_POINTS;
  } else {
    form.value.maxPoints = null;
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["levelRef"].validate(valid => {
    if (valid) {
      // 如果设置了无上限，将最高积分设为无上限值
      if (isUnlimited.value) {
        form.value.maxPoints = UNLIMITED_POINTS;
      }
      
      if (form.value.id != null) {
        updateLevel(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLevel(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 停用按钮操作 */
function handleDisable(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm(`是否确认停用用户积分等级规则编号为"${_ids}"的数据项？`).then(function() {
    return disableLevel(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess(`停用成功`);
  }).catch(() => {});
}

/** 启用按钮操作 */
function handleEnable(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm(`是否确认启用用户积分等级规则编号为"${_ids}"的数据项？`).then(function() {
    return enableLevel(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("启用成功");
  }).catch(() => {});
}



/** 导出按钮操作 */
function handleExport() {
  proxy.download('level/level/export', {
    ...queryParams.value
  }, `level_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style scoped>
.level-status :deep(.el-select) {
  width: 180px; 
}
.system-name :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 100px;
}
.min-points :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 100px;
}
.max-points :deep(.el-form-item__label) {
  white-space: nowrap;
  width: auto !important;
  min-width: 100px;
}
</style>